﻿using Dapper;
using Estsh.Core.Base;
using Estsh.Core.Dapper;
using Estsh.Core.Wms.IRepositories;
using Estsh.Core.Model.Result;
using Estsh.Core.Repositories;
using System.Collections;
using System.Data;
using System.Text;
using System.Security.Cryptography;
using System.Text.Json;
using Estsh.Core.Models;
using Newtonsoft.Json.Linq;
using Estsh.Core.Model.EnumUtil;
using System.Linq;
using Estsh.Core.Model.Extend.Models;
using System.Data.SqlTypes;
using static Estsh.Core.Model.EnumUtil.WmsEnumUtil;
using Aspose.Cells;
using Estsh.Core.Model.Extend.IFModels;

namespace Estsh.Core.Wms.Repositories
{
    public class QcRepository : BaseRepository<BaseEntity>, IQcRepository
    {
        public QcRepository(DapperDbContext _dapperDbContext) : base(_dapperDbContext)
        {

        }

        /// <summary>
        /// 质检单选择订单列表
        /// </summary>
        /// <returns></returns>
        public List<WmsQcDetail> GetQCListing(string cartonno)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder getqcSQL = new StringBuilder(1024);

                if (cartonno == null || cartonno == "")
                {
                    getqcSQL.Append(@"
                                    select    DISTINCT a.order_no ,
                                              a.vendor_id ,
                                              a.vendor_code ,
                                              a.ref_order_no ,
                                              a.remark ,
                                              a.factory_id ,
                                              a.factory_code ,
                                    		  a.create_userid ,
                                              a.create_time ,
                                    (CASE a.order_status
                                    	WHEN 10 THEN '创建'
                                    	WHEN 20 THEN '处理中' 
                                    	END)order_status
                                     from wms_qc_header (nolock) a INNER JOIN dbo.wms_qc_result r ON a.order_no=r.order_no
									  where a.order_status in ('10','20')");
                }
                else
                {
                    getqcSQL.Append(@"
                                    select    DISTINCT a.order_no ,
                                              a.vendor_id ,
                                              a.vendor_code ,
                                              a.ref_order_no ,
                                              a.remark ,
                                              a.factory_id ,
                                              a.factory_code ,
                                    		  a.create_userid ,
                                              a.create_time ,
                                    (CASE a.order_status
                                    	WHEN 10 THEN '创建'
                                    	WHEN 20 THEN '处理中' 
                                    	END)order_status
                                     from wms_qc_header (nolock) a INNER JOIN dbo.wms_qc_result r ON a.order_no=r.order_no
									  where a.order_status in ('10','20') and a.order_no like '%" + cartonno + "%' order by a.create_time desc");
                }

                    
                List<WmsQcDetail> WmsQcDetail = dbConn.Query<WmsQcDetail>(getqcSQL.ToString()).ToList();

                return WmsQcDetail;
            }
        }

        //订单收货情况
        public List<WmsQcShowList> GetShowList(string receving, string loginId)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder getqcSQL = new StringBuilder(1024);
                getqcSQL.Append(@"select DISTINCT * from wms_qc_result (nolock) where order_no = @order_no AND enabled='Y'");
                DynamicParameters Qcparameters = new DynamicParameters();
                Qcparameters.Add("@order_no", receving);
                List<WmsQcResult> WmsQcResult = dbConn.Query<WmsQcResult>(getqcSQL.ToString(), Qcparameters).ToList();

                List<WmsQcShowList> showlist = new List<WmsQcShowList>();
                if (WmsQcResult.Count > 0)
                {                  
                    //去重 分组统计零件
                    //List<WmsQcResult> partDetail = WmsQcResult.Distinct(new PartIdCompare()).ToList();
                    for (int i = 0; i < WmsQcResult.Count; i++)
                    {
                        int PartId = WmsQcResult[i].PartId;
                        //质检总数
                        int qtySum = WmsQcResult.Where(a => a.PartId == PartId && a.Enabled == "Y").Sum(s => s.Qty);
                        //未质检总数
                        int qty10 = WmsQcResult.Where(a => a.PartId == PartId && a.Enabled == "Y").Sum(s => s.surplusQty);
                        //合格总数
                        int OkQty = WmsQcResult.Where(a => a.PartId == PartId && a.Enabled == "Y").Sum(s => s.OkQty);
                        //不良总数
                        int NcQty = WmsQcResult.Where(a => a.PartId == PartId && a.Enabled == "Y").Sum(s => s.NcQty);

                        WmsQcShowList list = new WmsQcShowList();
                        list.OrderNo = WmsQcResult[i].OrderNo;
                        list.partSpec = WmsQcResult[i].PartSpec;
                        list.PartId = PartId;
                        list.PartNo = WmsQcResult[i].PartNo;
                        list.QtySum = qtySum;
                        list.qty10 = NcQty - qty10;
                        list.OkQty = OkQty;
                        list.NcQty = NcQty;
                        showlist.Add(list);
                    }
                }

                return showlist;
            }
        }

        /// <summary>
        /// 获取质检结果
        /// </summary>
        /// <param name="receving"></param>
        /// <param name="loginId"></param>
        /// <returns></returns>
        public int GetQcRusult(string receving, string loginId)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                int sunOrderQty = 0;
                int sunOrderOKQty = 0;
                int sunOrderNcQty = 0;
                int qcResult = 0;

                StringBuilder getqcSQL = new StringBuilder(1024);
                getqcSQL.Append(@"select DISTINCT * from wms_qc_result (nolock) where order_no = @order_no AND enabled='Y'");
                DynamicParameters Qcparameters = new DynamicParameters();
                Qcparameters.Add("@order_no", receving);
                List<WmsQcResult> WmsQcResult = dbConn.Query<WmsQcResult>(getqcSQL.ToString(), Qcparameters).ToList();

                List<WmsQcShowList> showlist = new List<WmsQcShowList>();
                if (WmsQcResult.Count > 0)
                {
                    for (int i = 0; i < WmsQcResult.Count; i++)
                    {
                        int PartId = WmsQcResult[i].PartId;
                        //质检总数
                        int qtySum = WmsQcResult.Where(a => a.PartId == PartId && a.Enabled == "Y").Sum(s => s.Qty);
                        //未质检总数
                        int qty10 = WmsQcResult.Where(a => a.PartId == PartId && a.Enabled == "Y" && a.ItemStatus == "10").Sum(s => s.surplusQty);
                        //合格总数
                        int OkQty = WmsQcResult.Where(a => a.PartId == PartId && a.Enabled == "Y" && a.ItemStatus == "10").Sum(s => s.OkQty);
                        //不良总数
                        int NcQty = WmsQcResult.Where(a => a.PartId == PartId && a.Enabled == "Y").Sum(s => s.NcQty);

                        WmsQcShowList list = new WmsQcShowList();
                        list.OrderNo = WmsQcResult[i].OrderNo;
                        list.partSpec = WmsQcResult[i].PartSpec;
                        list.PartId = PartId;
                        list.PartNo = WmsQcResult[i].PartNo;
                        list.QtySum = qtySum;
                        list.qty10 = qtySum - qty10;
                        list.OkQty = OkQty;
                        list.NcQty = NcQty;
                        showlist.Add(list);

                        sunOrderQty = sunOrderQty + list.QtySum;
                        sunOrderOKQty = sunOrderOKQty + list.OkQty;
                        sunOrderNcQty = sunOrderNcQty + list.NcQty;
                    }

                }
                if (sunOrderNcQty == 0)
                {
                    //整单合格
                    qcResult = 1;
                }
                else if (sunOrderOKQty == 0)
                {
                    //整单不良
                    qcResult = 2;
                }
                else if (sunOrderNcQty > 0 && sunOrderNcQty < sunOrderQty)
                {
                    //部分不良
                    qcResult = 3;
                }
                return qcResult;
            }
        }

        //完成质检
        public string CheckQc(string receving, string loginId, string remark,string qcresult)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                int stockStatus = 40;  //合格，待上架

                dbConn.Open();

                List<string> sqlStrings = new List<string>();
                List<DynamicParameters> parameterList = new List<DynamicParameters>();

                //更改质检明细表状态  20 已完成
                StringBuilder updateString = new StringBuilder(1024);
                updateString.Append("update wms_qc_detail set item_status='20',update_userid=@update_userid,remark= isnull(remark,'') + @remark,update_time=@update_time  where order_no= @order_no and item_status != '30' ");
                DynamicParameters updateStringparameters = new DynamicParameters();
                updateStringparameters.Add("@order_no", receving);
                updateStringparameters.Add("@update_userid", loginId);
                updateStringparameters.Add("@remark", remark);
                updateStringparameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                sqlStrings.Add(updateString.ToString());
                parameterList.Add(updateStringparameters);

                //更改质检表状态 30 已完成
                StringBuilder updateString2 = new StringBuilder(1024);
                updateString2.Append("update wms_qc_header set order_status='30',update_userid=@update_userid,remark=isnull(remark,'') + @remark,update_time=@update_time  where order_no= @order_no ");
                DynamicParameters updateStringparameters2 = new DynamicParameters();
                updateStringparameters2.Add("@order_no", receving);
                updateStringparameters2.Add("@update_userid", loginId);
                updateStringparameters2.Add("@remark", remark);
                updateStringparameters2.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                sqlStrings.Add(updateString2.ToString());
                parameterList.Add(updateStringparameters2);

                //判断质检结果
                if (qcresult == "2"){  //整单不良
                    stockStatus = 150;

                    //生成供应商退货单
                    updateString = new StringBuilder(1024);
                    updateString.Append("SELECT * FROM dbo.wms_qc_detail WHERE order_no=@order_no AND enabled='Y' AND item_status!=30 ");
                    DynamicParameters parameters = new DynamicParameters();
                    parameters.Add("@order_no", receving);
                    List<WmsQcDetail> qcDetailInfo = dbConn.Query<WmsQcDetail>(updateString.ToString(), parameters).ToList();

                    for (int i = 0; i < qcDetailInfo.Count; i++)
                    {
                        //List<string> sqlList = new List<string>();
                        StringBuilder SqlStringBuilder = new StringBuilder(1024);
                        //List<DynamicParameters> parametersList = new List<DynamicParameters>();
                        parameters = new DynamicParameters();
                        SqlStringBuilder.Append("INSERT INTO dbo.wms_outstock_detail(order_no,item_no,part_id,part_no,part_spec,qty,pick_qty,out_qty,unit ");
                        SqlStringBuilder.Append("           ,plan_date,plan_time,item_status,src_warehouse_id,src_warehouse_name,src_zone_id,src_zone_name ");
                        SqlStringBuilder.Append("           ,src_locate_id,src_locate_name,src_erp_warehouse,factory_id,factory_code,enabled ");
                        SqlStringBuilder.Append("           ,create_userid,create_time) ");
                        SqlStringBuilder.Append("     VALUES(@orderNo,@itemNo,@partId,@partNo,@partSpec,@qty,@pickQty,@outQty,@unit,@planDate ");
                        SqlStringBuilder.Append("           ,'',@itemStatus,0,'',0,'' ");
                        SqlStringBuilder.Append("           ,0,'',@srcErpWarehouse,@factoryId,@factoryCode,@enabled ");
                        SqlStringBuilder.Append("           ,@createUserid,@createTime) ");
                        sqlStrings.Add(SqlStringBuilder.ToString());

                        parameters = new DynamicParameters();
                        parameters.Add("@orderNo", receving);//销售交货单
                        parameters.Add("@itemNo", i);//PO item
                        parameters.Add("@partId", qcDetailInfo[i].PartId);//物料Id
                        parameters.Add("@partSpec", qcDetailInfo[i].PartSpec);//物料描述
                        parameters.Add("@partNo", qcDetailInfo[i].PartNo);//物料编码

                        parameters.Add("@qty", 0);//交货数量
                        parameters.Add("@pickQty", 0);//
                        parameters.Add("@outQty", qcDetailInfo[i].Qty);//

                        parameters.Add("@unit", "EA");//单位

                        parameters.Add("@planDate", DateTime.Now.ToString("yyyy-MM-dd"));//计划交货日期
         
                        parameters.Add("@itemStatus", 10);//状态
                        parameters.Add("@srcErpWarehouse", null);//库存地

                        parameters.Add("@factoryId", qcDetailInfo[i].FactoryId);//工厂ID
                        parameters.Add("@factoryCode", qcDetailInfo[i].FactoryCode);//工厂代码
                        parameters.Add("@enabled", 'Y');//启用
                        parameters.Add("@createUserid", qcDetailInfo[i].UpdateUserId);//创建人
                        parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                        parameterList.Add(parameters);
                    }

                    updateString = new StringBuilder(1024);
                    updateString.Append("SELECT * FROM dbo.wms_qc_header WHERE order_no=@order_no AND enabled='Y' AND order_status!=30 ");
                    parameters = new DynamicParameters();
                    parameters.Add("@order_no", receving);
                    List<WmsQcHeader> qcHeaderInfo = dbConn.Query<WmsQcHeader>(updateString.ToString(), parameters).ToList();
                    for (int i = 0; i < qcHeaderInfo.Count; i++)
                    {
                        //List<string> sqlList = new List<string>();
                        StringBuilder SqlStringBuilder = new StringBuilder(1024);
                        //List<DynamicParameters> parametersList = new List<DynamicParameters>();
                        parameters = new DynamicParameters();
                        SqlStringBuilder.Append("INSERT INTO dbo.wms_outstock(order_no,order_type,order_status,vendor_id,vendor_code,customer_id ");
                        SqlStringBuilder.Append("           ,customer_code,factory_id,factory_code,enabled,create_userid,create_time,guid) ");
                        SqlStringBuilder.Append("     VALUES(@orderNo,@orderType,@orderStatus,0,'',@customerId,@customerCode ");
                        SqlStringBuilder.Append("           ,@factoryId,@factoryCode,@enabled,@createUserid,@createTime,@guid) ");
                        sqlStrings.Add(SqlStringBuilder.ToString());

                        parameters = new DynamicParameters();
                        parameters.Add("@orderNo", qcHeaderInfo[i].OrderNo);//销售交货单
                        parameters.Add("@orderType", (int)WmsEnumUtil.OutStockType.SUPPLIER_RETURN);//类型
                        parameters.Add("@orderStatus", (int)WmsEnumUtil.MoveOrderStatus.CREATE);//状态
                        parameters.Add("@customerId", 0);//客户ID
                        parameters.Add("@customerCode", null);//客户代码
                        parameters.Add("@factoryId", qcHeaderInfo[i].FactoryId);//工厂ID
                        parameters.Add("@factoryCode", qcHeaderInfo[i].FactoryCode);//工厂代码
                        parameters.Add("@enabled", 'Y');//启用
                        parameters.Add("@createUserid", qcHeaderInfo[i].UpdateUserId);//创建人
                        parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                        parameters.Add("@guid", new Guid());//guid

                        parameterList.Add(parameters);
                    }
                }
                if (qcresult == "3")  //部分不良
                {
                    updateString = new StringBuilder(1024);
                    updateString.Append("SELECT * FROM dbo.wms_qc_result WHERE order_no=@order_no AND enabled='Y' AND surplusQty!=0 ");
                    DynamicParameters parameters = new DynamicParameters();
                    parameters.Add("@order_no", receving);
                    List<WmsQcResult> resInfo = dbConn.Query<WmsQcResult>(updateString.ToString(), parameters).ToList();
                    if (resInfo.Count != 0)
                    {
                        return "请质检完成后进行提交";
                    }
                }
                
                //更改条码表箱 条码状态为 40
                    StringBuilder sql = new StringBuilder(1024);
                sql.Append("select * from sys_stock(NOLOCK)   where carton_no in ( select carton_no from wms_qc_detail  where order_no= @order_no and item_status != '30') AND status!=180 ");
                DynamicParameters parameters2 = new DynamicParameters();
                parameters2.Add("@order_no", receving);
                List<SysStock> sysStocks = dbConn.Query<SysStock>(sql.ToString(), parameters2).ToList();

                for (int i = 0; i < sysStocks.Count; i++)
                {
                    StringBuilder updateString3 = new StringBuilder(1024);
                    updateString3.Append("update sys_stock set status=@status,update_userid=@update_userid,update_time=@update_time,QCfinishTime=@QCfinishTime  where carton_no= @carton_no ");
                    DynamicParameters updateStringparameters3 = new DynamicParameters();
                    updateStringparameters3.Add("@carton_no", sysStocks[i].CartonNo);
                    updateStringparameters3.Add("@status", stockStatus);
                    updateStringparameters3.Add("@update_userid", loginId);
                    updateStringparameters3.Add("@QCfinishTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    updateStringparameters3.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                    sqlStrings.Add(updateString3.ToString());
                    parameterList.Add(updateStringparameters3);

                    //新增 sys_stock_trans 事务表
                    StringBuilder updateString4 = new StringBuilder(1024);
                    updateString4.Append(@" INSERT INTO[dbo].[sys_stock_trans]
                                                    ([trans_code]
                                                    ,[carton_no]
                                                    ,[part_id]
                                                    ,[part_no]
                                                    ,[part_spec]
                                                    ,[src_locate_id]
                                                    ,[src_locate_name]
                                                    ,[dest_locate_id]
                                                    ,[dest_locate_name]
                                                    ,[old_qty]
                                                    ,[new_qty]
                                                    ,[trans_qty]
                                                    ,[old_status]
                                                    ,[new_status]
                                                    ,[old_qms_status]
                                                    ,[new_qms_status]
                                                    ,[unit]
                                                    ,[factory_id]
                                                    ,[factory_code]
                                                    ,[src_erp_warehouse]
                                                    ,[dest_erp_warehouse]
                                                    ,[src_warehouse_id]
                                                    ,[src_warehouse_name]
                                                    ,[dest_warehouse_id]
                                                    ,[dest_warehouse_name]
                                                    ,[src_zone_id]
                                                    ,[src_zone_name]
                                                    ,[dest_zone_id]
                                                    ,[dest_zone_name]
                                                    ,[enabled]
                                                    ,[update_userid]
                                                    ,[update_time]
                                                    ,[create_userid]
                                                    ,[create_time]
                                                    ,[guid])
                                                  VALUES (@trans_code,@carton_no,@part_id,@part_no,@part_spec,@src_locate_id ,@src_locate_name ,@dest_locate_id ,@dest_locate_name ,@old_qty 
                                        ,@new_qty ,@trans_qty ,@old_status ,@new_status ,@old_qms_status ,@new_qms_status ,@unit ,@factory_id ,@factory_code ,@src_erp_warehouse ,@dest_erp_warehouse ,@src_warehouse_id ,@src_warehouse_name ,@dest_warehouse_id ,@dest_warehouse_name ,@src_zone_id ,@src_zone_name ,@dest_zone_id ,@dest_zone_name ,@enabled ,@update_userid ,@update_time ,@create_userid ,@create_time ,@guid )");

                    DynamicParameters updateStringparameters4 = new DynamicParameters();
                    updateStringparameters4.Add("@trans_code", 50);
                    updateStringparameters4.Add("@carton_no", sysStocks[i].CartonNo);
                    updateStringparameters4.Add("@part_id", sysStocks[i].PartId);
                    updateStringparameters4.Add("@part_no", sysStocks[i].PartNo);
                    updateStringparameters4.Add("@part_spec", sysStocks[i].PartSpec);
                    updateStringparameters4.Add("@src_locate_id", 0);
                    updateStringparameters4.Add("@src_locate_name", null);
                    updateStringparameters4.Add("@dest_locate_id", 0);
                    updateStringparameters4.Add("@dest_locate_name", null);
                    updateStringparameters4.Add("@old_qty", sysStocks[i].Qty);
                    updateStringparameters4.Add("@new_qty", sysStocks[i].Qty);
                    updateStringparameters4.Add("@trans_qty", sysStocks[i].Qty);
                    updateStringparameters4.Add("@old_status", sysStocks[i].Status);
                    updateStringparameters4.Add("@new_status", 40);
                    updateStringparameters4.Add("@old_qms_status", 10);
                    updateStringparameters4.Add("@new_qms_status", 20);
                    updateStringparameters4.Add("@unit", sysStocks[i].Unit);
                    updateStringparameters4.Add("@factory_id", sysStocks[i].FactoryId);
                    updateStringparameters4.Add("@factory_code", sysStocks[i].FactoryCode);
                    updateStringparameters4.Add("@src_erp_warehouse", sysStocks[i].ErpWarehouse);
                    updateStringparameters4.Add("@dest_erp_warehouse", sysStocks[i].ErpWarehouse);
                    updateStringparameters4.Add("@src_warehouse_id", sysStocks[i].WarehouseId);
                    updateStringparameters4.Add("@src_warehouse_name", sysStocks[i].WarehouseName);
                    updateStringparameters4.Add("@dest_warehouse_id", sysStocks[i].WarehouseId);
                    updateStringparameters4.Add("@dest_warehouse_name", sysStocks[i].WarehouseName);
                    updateStringparameters4.Add("@src_zone_id", sysStocks[i].ZoneId);
                    updateStringparameters4.Add("@src_zone_name", sysStocks[i].ZoneName);
                    updateStringparameters4.Add("@dest_zone_id", sysStocks[i].ZoneId);
                    updateStringparameters4.Add("@dest_zone_name", sysStocks[i].ZoneName);
                    updateStringparameters4.Add("@enabled", sysStocks[i].Enabled);
                    updateStringparameters4.Add("@update_userid", loginId);
                    updateStringparameters4.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    updateStringparameters4.Add("@create_userid", loginId);
                    updateStringparameters4.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    updateStringparameters4.Add("@guid", Guid.NewGuid());

                    sqlStrings.Add(updateString4.ToString());
                    parameterList.Add(updateStringparameters4);
                }

                //写进接口表，将质检合格的传给ERP
                //StringBuilder sql3 = new StringBuilder(1024);
                //sql3.Append("select order_no,part_no,sum(qty) qty ,sum(nc_qty) nc_qty from wms_qc_detail  where order_no=@order_no group by part_no,order_no");
                //DynamicParameters sql3parameters = new DynamicParameters();
                //sql3parameters.Add("@order_no", receving);
                //List<WmsQcDetail> qcDetails = dbConn.Query<WmsQcDetail>(sql3.ToString(), sql3parameters).ToList();

                //List<WmsPurchase> getorder = getOrderType(qcDetails[0].OrderNo);
                //for (int i = 0; i < qcDetails.Count; i++)
                //{
                //    StringBuilder insertSAPQC = new StringBuilder(1024);
                //    insertSAPQC.Append(@" INSERT INTO [dbo].[WMS_INQC]
                //                          ([BSTYP]
                //                          ,[EVRTN]
                //                          ,[ETENR]
                //                          ,[ZDEV]
                //                          ,[LGORT]
                //                          ,[UNIT]
                //                          ,[ZPOST]
                //                          ,[ZTIME]
                //                          ,[WERKS]
                //                          ,[MATNR]
                //                          ,[LIFNR]
                //                          ,[SID]
                //                          ,[ACTTIM]
                //                          ,[ACTUSR],[prove])
                //                            VALUES(@BSTYP,@EVRTN,@ETENR,@ZDEV,@LGORT,@UNIT,@ZPOST,@ZTIME,@WERKS,@MATNR,@LIFNR,@SID,@ACTTIM,@ACTUSR,@prove)");

                //    DynamicParameters insertSAPQCparameters = new DynamicParameters();
                //    insertSAPQCparameters.Add("@BSTYP", getorder[0].OrderType == (int)WmsEnumUtil.PurchaseOrderType.PO ? "F" : "L");
                //    insertSAPQCparameters.Add("@EVRTN", getorder[0].OrderNo.Trim());
                //    insertSAPQCparameters.Add("@SID", Guid.NewGuid().ToString().Replace("-", ""));
                //    insertSAPQCparameters.Add("@ETENR", getItemNo(getorder[0].OrderNo, qcDetails[i].PartNo)[0].ItemNo);
                //    insertSAPQCparameters.Add("@ZDEV", qcDetails[i].Qty - qcDetails[i].NcQty);
                //    insertSAPQCparameters.Add("@LGORT", getItemNo(getorder[0].OrderNo, qcDetails[i].PartNo)[0].ErpWarehouse);
                //    insertSAPQCparameters.Add("@UNIT", getPart(qcDetails[i].PartNo)[0].Unit);
                //    insertSAPQCparameters.Add("@ACTTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                //    insertSAPQCparameters.Add("@ACTUSR", loginId);
                //    insertSAPQCparameters.Add("@ZPOST", DateTime.Now.ToString("yyyyMMdd"));
                //    insertSAPQCparameters.Add("@ZTIME", DateTime.Now.ToString("HHmmss"));
                //    insertSAPQCparameters.Add("@WERKS", getorder[0].FactoryCode);
                //    insertSAPQCparameters.Add("@MATNR", qcDetails[i].PartNo);
                //    insertSAPQCparameters.Add("@LIFNR", getorder[0].VendorCode);
                //    insertSAPQCparameters.Add("@prove", receving.Substring(4));

                //    sqlStrings.Add(insertSAPQC.ToString());
                //    parameterList.Add(insertSAPQCparameters);
                //}


                //执行事务
                IDbTransaction transaction = dbConn.BeginTransaction();

                bool successCount = true;
                for (int i = 0; i < sqlStrings.Count; i++)
                {
                    if (dbConn.Execute(sqlStrings[i], parameterList[i], transaction) < 1)
                    {
                        successCount = false;
                    }
                }
                if (successCount)
                {
                    transaction.Commit();
                    return "OK";
                }
                else
                {
                    transaction.Rollback();
                    return "操作失败，请重新尝试！";
                }
            }
        }

        /// <summary>
        /// 扫描不良数，进行拆分
        /// </summary>
        /// <param name="cartonNo"></param>
        /// <param name="loginId"></param>
        /// <param name="orderNo"></param>
        /// <returns></returns>
        public SetObjectDetail CheckNcQty(string cartonNo, string loginId, string orderNo,string ncQty)
        {
            SetObjectDetail rfInfo = new SetObjectDetail();
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                //获取原条码
                StringBuilder getqcSQL = new StringBuilder(1024);
                DynamicParameters Qcparameters = new DynamicParameters();
                getqcSQL.Append(@"SELECT * FROM dbo.sys_stock(NOLOCK) WHERE enabled='Y' AND carton_no=@carton_no ");
                Qcparameters.Add("@carton_no", cartonNo);
                SysStock sysStocksInfo2 = dbConn.Query<SysStock>(getqcSQL.ToString(), Qcparameters).ToList().FirstOrDefault();
                if (sysStocksInfo2.Qty < Convert.ToInt32(ncQty))
                {
                    rfInfo.type = "FAIL";
                    rfInfo.message = "[" + ncQty + "]:输入的数量不能大于条码的数量!";
                    return rfInfo;
                }

                //获取当前零件质检结果下的NC总数量
                 getqcSQL = new StringBuilder(1024);
                 Qcparameters = new DynamicParameters();
                getqcSQL.Append(@"SELECT * FROM dbo.wms_qc_result(NOLOCK) WHERE order_no=@order_no AND enabled='Y' AND part_no IN (SELECT part_no FROM dbo.wms_qc_detail(NOLOCK) WHERE enabled='Y' AND item_status =10  AND order_no=@order_no AND carton_no=@carton_no)");            
                Qcparameters.Add("@order_no", orderNo);
                Qcparameters.Add("@carton_no", cartonNo);
                List<WmsQcResult> WmsQcResultInfo = dbConn.Query<WmsQcResult>(getqcSQL.ToString(), Qcparameters).ToList();
                int surQty=WmsQcResultInfo.FirstOrDefault().surplusQty;
                int intNcQty = Convert.ToInt32(ncQty);
                if (intNcQty > surQty)
                {
                    rfInfo.type = "FAIL";
                    rfInfo.message = "请输入不良范围内的质检数量";
                    return rfInfo;
                }


                //获取此应质检单号下除此零件外是否全部完成
                getqcSQL = new StringBuilder(1024);
                Qcparameters = new DynamicParameters();
                getqcSQL.Append(@"SELECT * FROM dbo.wms_qc_result(NOLOCK) WHERE order_no=@order_no AND item_status=10 AND nc_qty!=0 AND enabled='Y' AND part_no NOT  IN (SELECT part_no FROM dbo.wms_qc_detail(NOLOCK) WHERE enabled='Y' AND item_status =10  AND order_no=@order_no AND carton_no=@carton_no)");
                Qcparameters.Add("@order_no", orderNo);
                Qcparameters.Add("@carton_no", cartonNo);
                List<WmsQcResult> WmsQcResultIsOk = dbConn.Query<WmsQcResult>(getqcSQL.ToString(), Qcparameters).ToList();

                //获取当前零件下的不良总数量
                getqcSQL = new StringBuilder(1024);
                Qcparameters = new DynamicParameters();
                getqcSQL.Append(@"SELECT SUM(nc_qty) AS NcQty FROM dbo.wms_qc_detail(NOLOCK) WHERE order_no=@order_no  AND item_status=10 AND enabled='Y' AND part_no IN (SELECT part_no FROM dbo.wms_qc_detail WHERE carton_no=@carton_no AND enabled='Y')");
                Qcparameters.Add("@order_no", orderNo);
                Qcparameters.Add("@carton_no", cartonNo);
                List<WmsQcDetail> WmsQcDetailInfo = dbConn.Query<WmsQcDetail>(getqcSQL.ToString(), Qcparameters).ToList();
                int sumDetailNcQty = WmsQcDetailInfo.FirstOrDefault().NcQty;

                //获取明细下的条码
                getqcSQL = new StringBuilder(1024);
                Qcparameters = new DynamicParameters();
                getqcSQL.Append(@"SELECT * FROM dbo.wms_qc_detail(NOLOCK) WHERE order_no=@order_no AND carton_no=@carton_no  AND item_status != 30 AND  enabled='Y'  ");
                Qcparameters.Add("@order_no", orderNo);
                Qcparameters.Add("@carton_no", cartonNo);
                List<WmsQcDetail> WmsQcDetailInfo2 = dbConn.Query<WmsQcDetail>(getqcSQL.ToString(), Qcparameters).ToList();
                int DetailQty = WmsQcDetailInfo2.FirstOrDefault().Qty;              
                int syDetailQty = DetailQty - intNcQty;  //剩余总数=总数-拆分数量

                //匹配明细下拆分的所有条码
                getqcSQL = new StringBuilder(1024);
                Qcparameters = new DynamicParameters();
                getqcSQL.Append(@"SELECT MAX(carton_no) AS cartonNo FROM dbo.wms_qc_detail(NOLOCK) WHERE carton_no LIKE '"+ cartonNo + "%' ");
                //Qcparameters.Add("@carton_no", cartonNo);
                List<WmsQcDetail> WmsQccartonNo = dbConn.Query<WmsQcDetail>(getqcSQL.ToString(), Qcparameters).ToList();
                string qcCartonNo = WmsQccartonNo.FirstOrDefault().CartonNo;
                string strCartonNo;  //拆分后的条码
                if (DetailQty == intNcQty)
                {
                    strCartonNo = cartonNo;
                }
                else
                {
                    if (qcCartonNo.Contains("_"))
                    {
                        string oldCartonNo = qcCartonNo.Substring(0, qcCartonNo.Length - 4);
                        strCartonNo = qcCartonNo.Substring(qcCartonNo.Length - 3, 3);
                        int intCartonNo = Convert.ToInt32(strCartonNo);
                        intCartonNo++;
                        strCartonNo = oldCartonNo + "_" + intCartonNo.ToString("000");
                    }
                    else
                    {
                        strCartonNo = qcCartonNo + "_001";
                    }
                }


                getqcSQL = new StringBuilder(1024);
                Qcparameters = new DynamicParameters();
                getqcSQL.Append(@"SELECT * FROM dbo.wms_qc_result(NOLOCK) WHERE order_no=@order_no AND enabled='Y'");
                Qcparameters.Add("@order_no", orderNo);
                List<WmsQcDetail> WmsQcResultCount = dbConn.Query<WmsQcDetail>(getqcSQL.ToString(), Qcparameters).ToList();

                List<string> sqlStrings = new List<string>();
                List<DynamicParameters> parameterList = new List<DynamicParameters>();
                if (WmsQcResultInfo.Count > 0)
                {
                    WmsQcResultInfo.ForEach(item =>
                    {
                        //判断扫描条码的数量和拆分的数量是否一致，一致直接更新nc_qty为拆分的数量,状态为已完成；
                        if (DetailQty == intNcQty)
                        {
                            getqcSQL = new StringBuilder(1024);
                            getqcSQL.Append("update wms_qc_detail set item_status='20',nc_qty=@nc_qty,update_userid=@update_userid,update_time=@update_time  where order_no= @order_no AND carton_no=@carton_no  and item_status != '30' ");
                            Qcparameters = new DynamicParameters();
                            Qcparameters.Add("@order_no", orderNo);
                            Qcparameters.Add("@carton_no", cartonNo);
                            Qcparameters.Add("@nc_qty", intNcQty);
                            Qcparameters.Add("@update_userid", loginId);
                            Qcparameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                            sqlStrings.Add(getqcSQL.ToString());
                            parameterList.Add(Qcparameters);


                            //更新Stock状态 180 
                            getqcSQL = new StringBuilder(1024);
                            getqcSQL.Append("update sys_stock set " +
                                "relevance_order=@relevance_order,status='180',update_userid=@update_userid,update_time=@update_time,QCfinishTime=@QCfinishTime  where carton_no= @carton_no ");
                            Qcparameters = new DynamicParameters();
                            Qcparameters.Add("@carton_no", cartonNo);
                            Qcparameters.Add("@relevance_order", orderNo);
                            Qcparameters.Add("@update_userid", loginId);
                            Qcparameters.Add("@QCfinishTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            Qcparameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                            sqlStrings.Add(getqcSQL.ToString());
                            parameterList.Add(Qcparameters);
                        }
                        else
                        {
                            #region 拆分后，新增质检明细表
                            StringBuilder insertString2 = new StringBuilder(1024);
                            insertString2.Append(@"INSERT INTO [dbo].[wms_qc_detail]
                                                             ([order_no]
                                                             ,[part_id]
                                                             ,[part_no]
                                                             ,[part_spec]
                                                             ,[carton_no]
                                                             ,[lot_no]
                                                             ,[qty]
                                                             ,[nc_qty]
                                                             ,[item_status]
                                                             ,[remark]
                                                             ,[factory_id]
                                                             ,[factory_code]
                                                             ,[enabled]
                                                             ,[create_userid]
                                                             ,[create_time]
                                                             ,[update_userid]
                                                             ,[update_time]
                                                             ,[guid])
                                                            VALUES (@order_no,@part_id,@part_no,@part_spec,@carton_no,@lot_no,@qty,@nc_qty,@item_status,@remark,@factory_id,@factory_code
                ,@enabled,@create_userid,@create_time,@update_userid,@update_time,@guid) ");

                            DynamicParameters insertStringparameters2 = new DynamicParameters();
                            insertStringparameters2.Add("@order_no", orderNo);
                            insertStringparameters2.Add("@part_id", item.PartId);
                            insertStringparameters2.Add("@part_no", item.PartNo);
                            insertStringparameters2.Add("@part_spec", item.PartSpec);
                            insertStringparameters2.Add("@carton_no", strCartonNo);
                            insertStringparameters2.Add("@lot_no", item.LotNo);
                            insertStringparameters2.Add("@qty", ncQty);
                            insertStringparameters2.Add("@nc_qty", ncQty);
                            insertStringparameters2.Add("@item_status", 180);  //质检不合格
                            insertStringparameters2.Add("@remark", null);
                            insertStringparameters2.Add("@factory_id", item.FactoryId);
                            insertStringparameters2.Add("@factory_code", item.FactoryCode);
                            insertStringparameters2.Add("@enabled", "Y");
                            insertStringparameters2.Add("@update_userid", loginId);
                            insertStringparameters2.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            insertStringparameters2.Add("@create_userid", loginId);
                            insertStringparameters2.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            insertStringparameters2.Add("@guid", Guid.NewGuid());
                            sqlStrings.Add(insertString2.ToString());
                            parameterList.Add(insertStringparameters2);
                            #endregion

                            
                            //获取原条码
                            getqcSQL = new StringBuilder(1024);
                            Qcparameters = new DynamicParameters();
                            getqcSQL.Append(@"SELECT * FROM dbo.sys_stock(NOLOCK) WHERE enabled='Y' AND carton_no=@carton_no ");
                            Qcparameters.Add("@carton_no", cartonNo);
                            SysStock sysStocksInfo = dbConn.Query<SysStock>(getqcSQL.ToString(), Qcparameters).ToList().FirstOrDefault(); ;
                            if (sysStocksInfo != null)
                            {
                                #region 插入拆分出的箱条码
                                getqcSQL = new StringBuilder(1024);
                                getqcSQL.Append(@" INSERT INTO [dbo].[sys_stock]
                                        ([vendor_id]
                                        ,[vendor_code]
                                        ,[carton_no]
                                        ,[part_id]
                                        ,[part_no]
                                        ,[part_spec]
                                        ,[lot_no]
                                        ,[fix_lot_no]
                                        ,[status]
                                        ,[qty]
                                        ,[snp_qty]
                                        ,[locate_id]
                                        ,[locate_name]
                                        ,[group_no]
                                        ,[erp_warehouse]
                                        ,[date_code]
                                        ,[qms_status]
                                        ,[ref_order_no]
                                        ,[unit]
                                        ,[dock]
                                        ,[warehouse_id]
                                        ,[warehouse_name]
                                        ,[zone_id]
                                        ,[zone_name]
                                        ,[printed]
                                        ,[print_time]
                                        ,[remark]
                                        ,[factory_id]
                                        ,[factory_code]
                                        ,[enabled]
                                        ,[create_userid]
                                        ,[create_time]
                                        ,[update_userid]
                                        ,[update_time]
                                        ,[guid]
                                        ,[relevance_order])
                                        VALUES(@vendor_id,@vendor_code,@carton_no,@part_id,@part_no,@part_spec,@lot_no,@fix_lot_no,@status,@qty,@snp_qty
,@locate_id,@locate_name,@group_no,@erp_warehouse,@date_code,@qms_status,@ref_order_no,@unit,@dock,@warehouse_id,@warehouse_name,@zone_id,@zone_name
,@printed,@print_time,@remark,@factory_id,@factory_code,@enabled,@create_userid,@create_time,@update_userid,@update_time,@guid,@relevance_order )");

                                Qcparameters = new DynamicParameters();
                                Qcparameters.Add("@vendor_id", sysStocksInfo.VendorId);
                                Qcparameters.Add("@vendor_code", sysStocksInfo.VendorName);
                                Qcparameters.Add("@carton_no", strCartonNo);
                                Qcparameters.Add("@part_id", sysStocksInfo.PartId);
                                Qcparameters.Add("@part_no", sysStocksInfo.PartNo);
                                Qcparameters.Add("@part_spec", sysStocksInfo.PartSpec);
                                Qcparameters.Add("@lot_no", sysStocksInfo.LotNo);
                                Qcparameters.Add("@fix_lot_no", sysStocksInfo.FixLotNo);
                                Qcparameters.Add("@status", 180);
                                Qcparameters.Add("@qty", ncQty);
                                Qcparameters.Add("@snp_qty", sysStocksInfo.SnpQty);
                                Qcparameters.Add("@locate_id", sysStocksInfo.LocateId);
                                Qcparameters.Add("@locate_name", sysStocksInfo.LocateName);
                                Qcparameters.Add("@group_no", sysStocksInfo.GroupNo);
                                Qcparameters.Add("@erp_warehouse", sysStocksInfo.ErpWarehouse);
                                Qcparameters.Add("@date_code", sysStocksInfo.DateCode);
                                Qcparameters.Add("@qms_status", sysStocksInfo.QmsStatus);
                                Qcparameters.Add("@ref_order_no", sysStocksInfo.RefOrderNo);
                                Qcparameters.Add("@unit", sysStocksInfo.Unit);
                                Qcparameters.Add("@dock", sysStocksInfo.Dock);
                                Qcparameters.Add("@warehouse_id", sysStocksInfo.WarehouseId);
                                Qcparameters.Add("@warehouse_name", sysStocksInfo.WarehouseName);
                                Qcparameters.Add("@zone_id", sysStocksInfo.ZoneId);
                                Qcparameters.Add("@zone_name", sysStocksInfo.ZoneName);
                                Qcparameters.Add("@printed", sysStocksInfo.Printed);
                                Qcparameters.Add("@print_time", null);
                                Qcparameters.Add("@remark", null);
                                Qcparameters.Add("@factory_id", sysStocksInfo.FactoryId);
                                Qcparameters.Add("@factory_code", sysStocksInfo.FactoryCode);
                                Qcparameters.Add("@enabled", "Y");
                                Qcparameters.Add("@update_userid", null);
                                Qcparameters.Add("@update_time", null);
                                Qcparameters.Add("@create_userid", loginId);
                                Qcparameters.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                Qcparameters.Add("@guid", Guid.NewGuid());
                                Qcparameters.Add("@relevance_order", orderNo);

                                sqlStrings.Add(getqcSQL.ToString());
                                parameterList.Add(Qcparameters);
                                #endregion
                            }


                            //更改质检明细表状态  20 已完成
                            getqcSQL = new StringBuilder(1024);
                            getqcSQL.Append("update wms_qc_detail set item_status='20',qty=@qty,nc_qty=@nc_qty,update_userid=@update_userid,update_time=@update_time  where order_no= @order_no AND carton_no=@carton_no and item_status != '30' ");
                            Qcparameters = new DynamicParameters();
                            Qcparameters.Add("@carton_no", cartonNo);
                            Qcparameters.Add("@order_no", orderNo);
                            Qcparameters.Add("@qty", syDetailQty);
                            Qcparameters.Add("@nc_qty", 0);
                            Qcparameters.Add("@update_userid", loginId);
                            Qcparameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                            sqlStrings.Add(getqcSQL.ToString());
                            parameterList.Add(Qcparameters);


                            //更新Stock状态 40 待上架
                            getqcSQL = new StringBuilder(1024);
                            getqcSQL.Append("update sys_stock set " +
                                "relevance_order=@relevance_order,qty=qty-@qty,status='40',update_userid=@update_userid,update_time=@update_time,QCfinishTime=@QCfinishTime  where carton_no= @carton_no ");
                            Qcparameters = new DynamicParameters();
                            Qcparameters.Add("@carton_no", cartonNo);
                            Qcparameters.Add("@relevance_order", orderNo);
                            Qcparameters.Add("@qty", intNcQty);  //更新拆分后的数量
                            Qcparameters.Add("@update_userid", loginId);
                            Qcparameters.Add("@QCfinishTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            Qcparameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                            sqlStrings.Add(getqcSQL.ToString());
                            parameterList.Add(Qcparameters);
                        }

                        //判断结果表中对应零件的不良总数，是否等于拆分的数量
                        if (item.surplusQty == intNcQty)
                        {
                            //更改质检结果表状态  20 已完成
                            getqcSQL = new StringBuilder(1024);
                            getqcSQL.Append("update wms_qc_result set item_status='20',surplusQty=@surplusQty,update_userid=@update_userid,update_time=@update_time  where order_no= @order_no and part_no = @part_no ");
                            Qcparameters = new DynamicParameters();
                            Qcparameters.Add("@order_no", orderNo);
                            Qcparameters.Add("@part_no", item.PartNo);
                            Qcparameters.Add("@surplusQty", item.surplusQty-intNcQty);
                            Qcparameters.Add("@update_userid", loginId);
                            Qcparameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                            sqlStrings.Add(getqcSQL.ToString());
                            parameterList.Add(Qcparameters);


                            //判断结果表中对应质检单号下的零件，是否全部已完成
                            if (WmsQcResultIsOk.Count == 0)
                            {
                                //更新质检主表状态30
                                getqcSQL = new StringBuilder(1024);
                                getqcSQL.Append("update wms_qc_header set order_status='30',update_userid=@update_userid,update_time=@update_time  where order_no= @order_no ");
                                Qcparameters = new DynamicParameters();
                                Qcparameters.Add("@order_no", orderNo);
                                Qcparameters.Add("@update_userid", loginId);
                                Qcparameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                                sqlStrings.Add(getqcSQL.ToString());
                                parameterList.Add(Qcparameters);

                                //更改质检明细表状态  20 已完成
                                getqcSQL = new StringBuilder(1024);
                                getqcSQL.Append("update wms_qc_detail set item_status='20',update_userid=@update_userid,update_time=@update_time  where order_no= @order_no and item_status != '30' ");
                                Qcparameters = new DynamicParameters();
                                Qcparameters.Add("@order_no", orderNo);
                                Qcparameters.Add("@update_userid", loginId);
                                Qcparameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                                sqlStrings.Add(getqcSQL.ToString());
                                parameterList.Add(Qcparameters);
                            }
                        }
                        else
                        {
                            int surplusQty = item.surplusQty - intNcQty;
                            //更新剩余拆分数量
                            getqcSQL = new StringBuilder(1024);
                            getqcSQL.Append("update wms_qc_result set surplusQty=@surplusQty,update_userid=@update_userid,update_time=@update_time  where order_no= @order_no and part_no = @part_no ");
                            Qcparameters = new DynamicParameters();
                            Qcparameters.Add("@surplusQty", surplusQty);
                            Qcparameters.Add("@order_no", orderNo);
                            Qcparameters.Add("@part_no", item.PartNo);
                            Qcparameters.Add("@update_userid", loginId);
                            Qcparameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                            sqlStrings.Add(getqcSQL.ToString());
                            parameterList.Add(Qcparameters);
                        }

                        if (sumDetailNcQty >= item.NcQty)
                        {
                            //更改质检结果表状态  20 已完成
                            getqcSQL = new StringBuilder(1024);
                            getqcSQL.Append("update wms_qc_result set item_status='20',update_userid=@update_userid,update_time=@update_time  where order_no= @order_no and part_no = @part_no ");
                            Qcparameters = new DynamicParameters();
                            Qcparameters.Add("@order_no", orderNo);
                            Qcparameters.Add("@part_no", item.PartNo);
                            Qcparameters.Add("@update_userid", loginId);                          
                            Qcparameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                            sqlStrings.Add(getqcSQL.ToString());
                            parameterList.Add(Qcparameters);
                        }


 


                        #region 新增 sys_stock_trans 事务表

                        getqcSQL = new StringBuilder(1024);
                        getqcSQL.Append(@" INSERT INTO[dbo].[sys_stock_trans]
                                                    ([trans_code]
                                                    ,[carton_no]
                                                    ,[part_id]
                                                    ,[part_no]
                                                    ,[part_spec]
                                                    ,[src_locate_id]
                                                    ,[src_locate_name]
                                                    ,[dest_locate_id]
                                                    ,[dest_locate_name]
                                                    ,[old_qty]
                                                    ,[new_qty]
                                                    ,[trans_qty]
                                                    ,[old_status]
                                                    ,[new_status]
                                                    ,[old_qms_status]
                                                    ,[new_qms_status]
                                                    ,[unit]
                                                    ,[factory_id]
                                                    ,[factory_code]
                                                    ,[src_erp_warehouse]
                                                    ,[dest_erp_warehouse]
                                                    ,[src_warehouse_id]
                                                    ,[src_warehouse_name]
                                                    ,[dest_warehouse_id]
                                                    ,[dest_warehouse_name]
                                                    ,[src_zone_id]
                                                    ,[src_zone_name]
                                                    ,[dest_zone_id]
                                                    ,[dest_zone_name]
                                                    ,[enabled]
                                                    ,[update_userid]
                                                    ,[update_time]
                                                    ,[create_userid]
                                                    ,[create_time]
                                                    ,[guid])
                                                  VALUES (@trans_code,@carton_no,@part_id,@part_no,@part_spec,@src_locate_id ,@src_locate_name ,@dest_locate_id ,@dest_locate_name ,@old_qty 
                                        ,@new_qty ,@trans_qty ,@old_status ,@new_status ,@old_qms_status ,@new_qms_status ,@unit ,@factory_id ,@factory_code ,@src_erp_warehouse ,@dest_erp_warehouse ,@src_warehouse_id ,@src_warehouse_name ,@dest_warehouse_id ,@dest_warehouse_name ,@src_zone_id ,@src_zone_name ,@dest_zone_id ,@dest_zone_name ,@enabled ,@update_userid ,@update_time ,@create_userid ,@create_time ,@guid )");

                        Qcparameters = new DynamicParameters();
                        Qcparameters.Add("@trans_code", 50);
                        Qcparameters.Add("@carton_no", cartonNo);
                        Qcparameters.Add("@part_id", item.PartId);
                        Qcparameters.Add("@part_no", item.PartNo);
                        Qcparameters.Add("@part_spec", item.PartSpec);
                        Qcparameters.Add("@src_locate_id", 0);
                        Qcparameters.Add("@src_locate_name", null);
                        Qcparameters.Add("@dest_locate_id", 0);
                        Qcparameters.Add("@dest_locate_name", null);
                        Qcparameters.Add("@old_qty", DetailQty);
                        Qcparameters.Add("@new_qty", syDetailQty);
                        Qcparameters.Add("@trans_qty", DetailQty);
                        Qcparameters.Add("@old_status", item.ItemStatus);
                        Qcparameters.Add("@new_status", 20);
                        Qcparameters.Add("@old_qms_status", 10);
                        Qcparameters.Add("@new_qms_status", 20);
                        Qcparameters.Add("@unit", "EA");
                        Qcparameters.Add("@factory_id", item.FactoryId);
                        Qcparameters.Add("@factory_code", item.FactoryCode);
                        Qcparameters.Add("@src_erp_warehouse", null);
                        Qcparameters.Add("@dest_erp_warehouse", null);
                        Qcparameters.Add("@src_warehouse_id", null);
                        Qcparameters.Add("@src_warehouse_name", null);
                        Qcparameters.Add("@dest_warehouse_id", null);
                        Qcparameters.Add("@dest_warehouse_name", null);
                        Qcparameters.Add("@src_zone_id", null);
                        Qcparameters.Add("@src_zone_name", null);
                        Qcparameters.Add("@dest_zone_id", null);
                        Qcparameters.Add("@dest_zone_name", null);
                        Qcparameters.Add("@enabled", item.Enabled);
                        Qcparameters.Add("@update_userid", loginId);
                        Qcparameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        Qcparameters.Add("@create_userid", loginId);
                        Qcparameters.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        Qcparameters.Add("@guid", Guid.NewGuid());

                        sqlStrings.Add(getqcSQL.ToString());
                        parameterList.Add(Qcparameters);

                        #endregion

                    });
                }
                else
                {
                    rfInfo.type = "FAIL";
                    rfInfo.message = "质检单[" + orderNo + "]无质检结果！";
                    return rfInfo;
                }

                //执行事务
                IDbTransaction transaction = dbConn.BeginTransaction();

                bool successCount = true;
                for (int i = 0; i < sqlStrings.Count; i++)
                {
                    if (dbConn.Execute(sqlStrings[i], parameterList[i], transaction) < 1)
                    {
                        successCount = false;
                    }
                }
                if (successCount)
                {
                    transaction.Commit();
                    StringBuilder stringBuilder = new StringBuilder(1024);
                    stringBuilder.Append("SELECT * FROM dbo.wms_qc_result WHERE order_no='"+orderNo+"' AND enabled='Y' AND item_status IN (10,20)");

                    List<WmsQcResult> qcResults = dbConn.Query<WmsQcResult>(stringBuilder.ToString()).ToList();
                    if (qcResults.Count > 0)
                    {
                        for (int i = 0; i < qcResults.Count; i++)
                        {
                            if (qcResults[i].surplusQty != 0)
                            {
                                rfInfo.type = "PASS";
                                rfInfo.message = "[" + cartonNo + "]:操作成功!请继续扫描箱条码";
                                rfInfo.wmsObjectDetail = qcResults.ConvertAll(s => (object)s);
                                return rfInfo;
                            }
                        }
                    }
                    rfInfo.type = "PASS";
                    rfInfo.message = "已质检完成，请点击按钮提交！";
                    return rfInfo;
                }
                else
                {
                    transaction.Rollback();
                    rfInfo.type = "FAIL";
                    rfInfo.message = "操作失败，请重新尝试！";
                    return rfInfo;
                }
            }
        }

        public string CheckCartonStatus(string cartonNo, string loginId, string orderNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                string result = string.Empty;

                StringBuilder sql = new StringBuilder(1024);
                sql.Append("select * from wms_qc_detail (nolock) where order_no = @order_no and carton_no=@carton_no and Enabled='Y' ");
                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("@carton_no", cartonNo);
                parameters.Add("@order_no", orderNo);
                List<WmsQcDetail> dt = dbConn.Query<WmsQcDetail>(sql.ToString(), parameters).ToList();
                
                if (dt.Count > 0)
                {
                    sql = new StringBuilder(1024);
                    sql.Append("SELECT * FROM dbo.sys_stock(NOLOCK) WHERE carton_no=@carton_no AND enabled='Y' ");
                    parameters = new DynamicParameters();
                    parameters.Add("@carton_no", dt.FirstOrDefault().CartonNo);
                    List<SysStock_Extend> dtStock = dbConn.Query<SysStock_Extend>(sql.ToString(), parameters).ToList();
                    if (dtStock.Count == 0)
                    {
                        return "[" + cartonNo + "]: 该条码不存在!";
                    }
                    if (dtStock.FirstOrDefault().Status != 30)
                    {
                        return "当前条码状态为[" + dtStock.FirstOrDefault().Status + "]不允许质检!";
                    }

                    List<WmsQcDetail> ifQc = dt.Where(a => a.CartonNo == cartonNo && a.ItemStatus == "10").ToList();

                    if (ifQc.Count > 0)
                    {
                        return "OK"; //+ ifQc[0].Qty;
                    }
                    else
                    {
                        return "[" + cartonNo + "]: 已质检!";
                    }
                }
                else
                {
                    return "[" + cartonNo + "]: 不在此质检单内!";
                }

            }
        }

        public string CheckQcCarton(string QcCartonNo, string MAXmessage, string loginId, string Remark, string receving)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();

                List<string> sqlStrings = new List<string>();
                List<DynamicParameters> parameterList = new List<DynamicParameters>();

                //更改质检明细表状态  30 拒收
                StringBuilder updateString = new StringBuilder(1024);
                updateString.Append("update wms_qc_detail set item_status='30',update_userid=@update_userid,remark= isnull(remark,'') + @remark,update_time=@update_time,nc_qty=@nc_qty  where carton_no= @carton_no and item_status != '30' ");
                DynamicParameters updateStringparameters = new DynamicParameters();
                updateStringparameters.Add("@carton_no", QcCartonNo);
                updateStringparameters.Add("@update_userid", loginId);
                updateStringparameters.Add("@remark", Remark);
                updateStringparameters.Add("@nc_qty", MAXmessage);
                updateStringparameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                sqlStrings.Add(updateString.ToString());
                parameterList.Add(updateStringparameters);

                //获取质检订单 条码信息
                StringBuilder sql = new StringBuilder(1024);
                sql.Append(@"select a.* from sys_stock as a (nolock) right join 
                            (select * from wms_qc_detail (nolock) where order_no = (
                             select distinct order_no from wms_qc_detail (nolock) where carton_no = @carton_no ) and item_status='10' ) as b
                             on a.carton_no = b.carton_no  where isnull(a.carton_no,'') != '' ");
                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("@carton_no", QcCartonNo);
                List<SysStock> sysStocks = dbConn.Query<SysStock>(sql.ToString(), parameters).ToList();


                if (sysStocks.Count > 0)
                {
                    //如果只有一条，质检明细表就是最后一条，需要将质检主表也进行状态变更
                    if (sysStocks.Count == 1)
                    {
                        //更改质检表状态 30 已完成
                        StringBuilder updateString2 = new StringBuilder(1024);
                        updateString2.Append("update wms_qc_header set order_status='30',update_userid=@update_userid,remark=isnull(remark,'') + @remark,update_time=@update_time  where order_no= @order_no ");
                        DynamicParameters updateStringparameters2 = new DynamicParameters();
                        updateStringparameters2.Add("@order_no", receving);
                        updateStringparameters2.Add("@update_userid", loginId);
                        updateStringparameters2.Add("@remark", "");
                        updateStringparameters2.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                        sqlStrings.Add(updateString2.ToString());
                        parameterList.Add(updateStringparameters2);
                    }
                }
                List<SysStock> sysStock = sysStocks.Where(a => a.CartonNo == QcCartonNo && a.Enabled == "Y").ToList();



                //新增 sys_stock_trans 事务表
                StringBuilder updateString4 = new StringBuilder(1024);
                updateString4.Append(@" INSERT INTO[dbo].[sys_stock_trans]
                                                    ([trans_code]
                                                    ,[carton_no]
                                                    ,[part_id]
                                                    ,[part_no]
                                                    ,[part_spec]
                                                    ,[src_locate_id]
                                                    ,[src_locate_name]
                                                    ,[dest_locate_id]
                                                    ,[dest_locate_name]
                                                    ,[old_qty]
                                                    ,[new_qty]
                                                    ,[trans_qty]
                                                    ,[old_status]
                                                    ,[new_status]
                                                    ,[old_qms_status]
                                                    ,[new_qms_status]
                                                    ,[unit]
                                                    ,[factory_id]
                                                    ,[factory_code]
                                                    ,[src_erp_warehouse]
                                                    ,[dest_erp_warehouse]
                                                    ,[src_warehouse_id]
                                                    ,[src_warehouse_name]
                                                    ,[dest_warehouse_id]
                                                    ,[dest_warehouse_name]
                                                    ,[src_zone_id]
                                                    ,[src_zone_name]
                                                    ,[dest_zone_id]
                                                    ,[dest_zone_name]
                                                    ,[enabled]
                                                    ,[update_userid]
                                                    ,[update_time]
                                                    ,[create_userid]
                                                    ,[create_time]
                                                    ,[guid])
                                                  VALUES (@trans_code,@carton_no,@part_id,@part_no,@part_spec,@src_locate_id ,@src_locate_name ,@dest_locate_id ,@dest_locate_name ,@old_qty 
                                        ,@new_qty ,@trans_qty ,@old_status ,@new_status ,@old_qms_status ,@new_qms_status ,@unit ,@factory_id ,@factory_code ,@src_erp_warehouse ,@dest_erp_warehouse ,@src_warehouse_id ,@src_warehouse_name ,@dest_warehouse_id ,@dest_warehouse_name ,@src_zone_id ,@src_zone_name ,@dest_zone_id ,@dest_zone_name ,@enabled ,@update_userid ,@update_time ,@create_userid ,@create_time ,@guid )");

                //更改条码表状态为 150 拒收
                if (sysStock.Count > 0)
                {
                    if (sysStock[0].Qty.ToString() == MAXmessage)
                    {
                        StringBuilder updateString3 = new StringBuilder(1024);
                        updateString3.Append("update sys_stock set status='150',update_userid=@update_userid,update_time=@update_time,QCfinishTime=@QCfinishTime  where carton_no= @carton_no ");
                        DynamicParameters updateStringparameters3 = new DynamicParameters();
                        updateStringparameters3.Add("@carton_no", QcCartonNo);
                        updateStringparameters3.Add("@update_userid", loginId);
                        updateStringparameters3.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        updateStringparameters3.Add("@QCfinishTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        sqlStrings.Add(updateString3.ToString());
                        parameterList.Add(updateStringparameters3);

                        //拒收事务
                        DynamicParameters updateStringparameters4 = new DynamicParameters();
                        updateStringparameters4.Add("@trans_code", sysStock[0].Status);
                        updateStringparameters4.Add("@carton_no", sysStock[0].CartonNo);
                        updateStringparameters4.Add("@part_id", sysStock[0].PartId);
                        updateStringparameters4.Add("@part_no", sysStock[0].PartNo);
                        updateStringparameters4.Add("@part_spec", sysStock[0].PartSpec);
                        updateStringparameters4.Add("@src_locate_id", 0);
                        updateStringparameters4.Add("@src_locate_name", null);
                        updateStringparameters4.Add("@dest_locate_id", 0);
                        updateStringparameters4.Add("@dest_locate_name", null);
                        updateStringparameters4.Add("@old_qty", sysStock[0].Qty);
                        updateStringparameters4.Add("@new_qty", sysStock[0].Qty);
                        updateStringparameters4.Add("@trans_qty", sysStock[0].Qty);
                        updateStringparameters4.Add("@old_status", sysStock[0].Status);
                        updateStringparameters4.Add("@new_status", 150);
                        updateStringparameters4.Add("@old_qms_status", 10);
                        updateStringparameters4.Add("@new_qms_status", 30);
                        updateStringparameters4.Add("@unit", sysStock[0].Unit);
                        updateStringparameters4.Add("@factory_id", sysStock[0].FactoryId);
                        updateStringparameters4.Add("@factory_code", sysStock[0].FactoryCode);
                        updateStringparameters4.Add("@src_erp_warehouse", sysStock[0].ErpWarehouse);
                        updateStringparameters4.Add("@dest_erp_warehouse", sysStock[0].ErpWarehouse);
                        updateStringparameters4.Add("@src_warehouse_id", sysStock[0].WarehouseId);
                        updateStringparameters4.Add("@src_warehouse_name", sysStock[0].WarehouseName);
                        updateStringparameters4.Add("@dest_warehouse_id", sysStock[0].WarehouseId);
                        updateStringparameters4.Add("@dest_warehouse_name", sysStock[0].WarehouseName);
                        updateStringparameters4.Add("@src_zone_id", sysStock[0].ZoneId);
                        updateStringparameters4.Add("@src_zone_name", sysStock[0].ZoneName);
                        updateStringparameters4.Add("@dest_zone_id", sysStock[0].ZoneId);
                        updateStringparameters4.Add("@dest_zone_name", sysStock[0].ZoneName);
                        updateStringparameters4.Add("@enabled", sysStock[0].Enabled);
                        updateStringparameters4.Add("@update_userid", loginId);
                        updateStringparameters4.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        updateStringparameters4.Add("@create_userid", loginId);
                        updateStringparameters4.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        updateStringparameters4.Add("@guid", Guid.NewGuid());

                        sqlStrings.Add(updateString4.ToString());
                        parameterList.Add(updateStringparameters4);
                    }
                    else
                    {
                        StringBuilder updateString3 = new StringBuilder(1024);
                        updateString3.Append("update sys_stock set status='40',qty =@qty,update_userid=@update_userid,update_time=@update_time,QCfinishTime=@QCfinishTime  where carton_no= @carton_no ");
                        DynamicParameters updateStringparameters3 = new DynamicParameters();
                        updateStringparameters3.Add("@carton_no", QcCartonNo);
                        updateStringparameters3.Add("@qty", sysStock[0].Qty - Convert.ToDecimal(MAXmessage));
                        updateStringparameters3.Add("@update_userid", loginId);
                        updateStringparameters3.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        updateStringparameters3.Add("@QCfinishTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        sqlStrings.Add(updateString3.ToString());
                        parameterList.Add(updateStringparameters3);
                        //拒收事务
                        DynamicParameters updateStringparameters4 = new DynamicParameters();
                        updateStringparameters4.Add("@trans_code", sysStock[0].Status);
                        updateStringparameters4.Add("@carton_no", sysStock[0].CartonNo);
                        updateStringparameters4.Add("@part_id", sysStock[0].PartId);
                        updateStringparameters4.Add("@part_no", sysStock[0].PartNo);
                        updateStringparameters4.Add("@part_spec", sysStock[0].PartSpec);
                        updateStringparameters4.Add("@src_locate_id", 0);
                        updateStringparameters4.Add("@src_locate_name", null);
                        updateStringparameters4.Add("@dest_locate_id", 0);
                        updateStringparameters4.Add("@dest_locate_name", null);
                        updateStringparameters4.Add("@old_qty", sysStock[0].Qty);
                        updateStringparameters4.Add("@new_qty", sysStock[0].Qty - Convert.ToDecimal(MAXmessage));
                        updateStringparameters4.Add("@trans_qty", sysStock[0].Qty);
                        updateStringparameters4.Add("@old_status", sysStock[0].Status);
                        updateStringparameters4.Add("@new_status", 40);
                        updateStringparameters4.Add("@old_qms_status", 10);
                        updateStringparameters4.Add("@new_qms_status", 30);
                        updateStringparameters4.Add("@unit", sysStock[0].Unit);
                        updateStringparameters4.Add("@factory_id", sysStock[0].FactoryId);
                        updateStringparameters4.Add("@factory_code", sysStock[0].FactoryCode);
                        updateStringparameters4.Add("@src_erp_warehouse", sysStock[0].ErpWarehouse);
                        updateStringparameters4.Add("@dest_erp_warehouse", sysStock[0].ErpWarehouse);
                        updateStringparameters4.Add("@src_warehouse_id", sysStock[0].WarehouseId);
                        updateStringparameters4.Add("@src_warehouse_name", sysStock[0].WarehouseName);
                        updateStringparameters4.Add("@dest_warehouse_id", sysStock[0].WarehouseId);
                        updateStringparameters4.Add("@dest_warehouse_name", sysStock[0].WarehouseName);
                        updateStringparameters4.Add("@src_zone_id", sysStock[0].ZoneId);
                        updateStringparameters4.Add("@src_zone_name", sysStock[0].ZoneName);
                        updateStringparameters4.Add("@dest_zone_id", sysStock[0].ZoneId);
                        updateStringparameters4.Add("@dest_zone_name", sysStock[0].ZoneName);
                        updateStringparameters4.Add("@enabled", sysStock[0].Enabled);
                        updateStringparameters4.Add("@update_userid", loginId);
                        updateStringparameters4.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        updateStringparameters4.Add("@create_userid", loginId);
                        updateStringparameters4.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        updateStringparameters4.Add("@guid", Guid.NewGuid());

                        sqlStrings.Add(updateString4.ToString());
                        parameterList.Add(updateStringparameters4);
                    }
                }



                //执行事务
                IDbTransaction transaction = dbConn.BeginTransaction();

                bool successCount = true;
                for (int i = 0; i < sqlStrings.Count; i++)
                {
                    if (dbConn.Execute(sqlStrings[i], parameterList[i], transaction) < 1)
                    {
                        successCount = false;
                    }
                }
                if (successCount)
                {
                    transaction.Commit();
                    return "OK";
                }
                else
                {
                    transaction.Rollback();
                    return "操作失败，请重新尝试！";
                }
            }
        }

        public List<WmsPurchase> getOrderType(string QCorderNo)
        {
            IDbConnection dbConn = dapperDbContext.GetDbConnection();
            StringBuilder sql = new StringBuilder(1024);
            sql.Append("select c.* from wms_qc_header as a (nolock) left join wms_purchase as c (nolock) on a.ref_order_no = c.order_no  where a.order_no = @orderNo");
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("@orderNo", QCorderNo);
            List<WmsPurchase> qcHeaders = dbConn.Query<WmsPurchase>(sql.ToString(), parameters).ToList();
            return qcHeaders;
        }

        public List<SysPart> getPart(string partNo)
        {
            IDbConnection dbConn = dapperDbContext.GetDbConnection();
            StringBuilder sql = new StringBuilder(1024);
            sql.Append("select * from sys_part (nolock) where part_no=@partNo");
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("@partNo", partNo);
            List<SysPart> getParts = dbConn.Query<SysPart>(sql.ToString(), parameters).ToList();
            return getParts;
        }
        public List<WmsPurchaseDetail> getItemNo(string orderNo, string partNo)
        {
            IDbConnection dbConn = dapperDbContext.GetDbConnection();
            StringBuilder sql = new StringBuilder(1024);
            sql.Append("select * from wms_purchase_detail (nolock) where order_no=@order_no and part_no=@partNo");
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("@order_no", orderNo);
            parameters.Add("@partNo", partNo);
            List<WmsPurchaseDetail> getPurchaseDetail = dbConn.Query<WmsPurchaseDetail>(sql.ToString(), parameters).ToList();
            return getPurchaseDetail;
        }
        public List<SysZone> getErpWareHouse()
        {
            IDbConnection dbConn = dapperDbContext.GetDbConnection();
            StringBuilder sql = new StringBuilder(1024);
            sql.Append("select a.erp_warehouse from sys_zone as a (nolock) left join sys_locate as b (nolock) on a.zone_id=b.zone_id where b.locate_type='50' ");
            List<SysZone> sysZones = dbConn.Query<SysZone>(sql.ToString()).ToList();
            return sysZones;
        }

        

        

        
    }
    public class PartIdCompare : IEqualityComparer<WmsQcDetail>
    {
        public bool Equals(WmsQcDetail x, WmsQcDetail y)
        {
            return x.PartId.Equals(y.PartId);
        }
        public int GetHashCode(WmsQcDetail obj)
        {
            return obj.PartId.GetHashCode();
        }
    }
}
